package com.woniuxy.service.impl;

import com.woniuxy.entity.TopicMail;
import com.woniuxy.service.DirectService;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

/**
 * @Author: 马宇航
 * @Description: TODO
 * @DateTime: 22/10/20/0020 11:43
 * @Component: 成都蜗牛学苑
 **/
@Service
public class DirectServiceImpl implements DirectService {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RabbitTemplate.ConfirmCallback confirmCallback;
    @Autowired
    RabbitTemplate.ReturnsCallback returnsCallback;
    @Override
    public void sendEmail(TopicMail mail) {
        //设置ConfirmCallBack的配置
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnsCallback(returnsCallback);
        //消息入库，所有发送的消息，需要存储到数据库中。防止消息丢失后，找不回消息。
        // CorrelationData这个参数就是封装对应数据库id，用于confirmCallback回调的时候，消息丢失。
        rabbitTemplate.convertAndSend("directExchange", mail.getRoutingkey(), mail, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //默认持久化
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                return message;
            }
        },new CorrelationData(mail.getMailId()));
    }
}
